package com.symone.webcms.controller.base;

import com.symone.webcms.common.ConstantProperties;
import com.symone.webcms.config.GlobalConfig;
import com.symone.webcms.model.UserLog;
import com.symone.webcms.model.vo.UserVO;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * com.symone.webcms.controller..*.*(..))")
    public void webLog(){

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.debug("URL : " + request.getRequestURL().toString());
        logger.debug("HTTP_METHOD : " + request.getMethod());
        logger.debug("IP : " + request.getRemoteAddr());
        String sys_log_method = GlobalConfig.getInstance().get("sys_log_method");
        if(StrUtil.isNotEmpty(sys_log_method) &&
                !Arrays.asList(sys_log_method.trim().toLowerCase().split(",")).contains(request.getMethod().toLowerCase())){
            return;
        }
        StringBuilder sb = new StringBuilder();
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            logger.debug("name:{},value:{}", name, request.getParameter(name));
            sb.append( name + "=" + request.getParameter(name));
            if(enu.hasMoreElements()){
                sb.append( ",");
            }
        }
        try {
            UserVO user = (UserVO) SecurityUtils.getSubject().getPrincipal();
            if(user != null) {
                // 记录下请求内容
                UserLog log = new UserLog();
                log.setIpAddress(request.getRemoteAddr());
                log.setUrl(request.getRequestURL().toString());
                log.setMethod(request.getMethod());
                log.setParams(sb.toString());
                log.setUserId(user.getId());
                log.setUserName(user.getUserName());
                log.insert();
            }
        }catch (Exception ex){
            logger.debug(ex.getMessage());
        }

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.debug("RESPONSE : " + ret);
    }
}